//
//  YH_CatMangeViewController.m
//  YinHang
//
//  Created by idea on 14-9-24.
//  Copyright (c) 2014年 孙彦鹏. All rights reserved.
//

#import "YH_CatMangeViewController.h"
#import "CatMangeCell.h"
#import "ShareSettingViewController.h"
#import "CatListService.h"

@interface YH_CatMangeViewController ()<UITableViewDelegate,UITableViewDataSource,CatListServiceDelegate,ASIHTTPRequestDelegate>{
    
    NSInteger selectedIndex;
    
    NSInteger selectRow;//选中行数
    
    MBProgressHUD *postHud;
    
    NSString *state;//判断状态
    
    __weak IBOutlet UIView *catnameChangeView;
    
    __weak IBOutlet UIView *catnameChangeViewSmall;
    
    __weak IBOutlet UITextField *newCatNameTF;
    
    __weak IBOutlet UILabel *catlblName;
    
    __weak IBOutlet UILabel *titlelbl;
    
    
    __weak IBOutlet UILabel *deleteLbl;
    
    __weak IBOutlet UIButton *cancelBtn;
    
    __weak IBOutlet UIButton *saveBtn;
    NSMutableArray *catMArr;
    NSIndexPath *_indexPath;//获取cell路径
    
    UIButton *rightBtn;//设置修改按钮
    
    CatListService *cls_;
    
    MBProgressHUD *loadHud;
    
    //参数
    NSString *action;
    NSDictionary *paramsDict;
    
    /* 删除信息请求 */
    ASIFormDataRequest *addCat;
    /* 删除信息请求 */
    ASIFormDataRequest *delegateCat;
    /* 修改类别名称请求 */
    ASIFormDataRequest *alterCat;
    

}

@end

@implementation YH_CatMangeViewController

#pragma mark - Life Cycle Method

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    
    self.navigationItem.title = @"类别管理";
    //返回
    UIButton *leftBtn = [[UIButton alloc]initWithFrame:CGRectMake(0, 0, 20, 30)];
    [leftBtn setBackgroundImage:[UIImage imageNamed:@"back"] forState:UIControlStateNormal];
    [leftBtn addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *leftBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:leftBtn];
    UIBarButtonItem *negativeSpacer = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:nil action:nil];
    negativeSpacer.width = - 10;
    if (ios7) {
        self.navigationItem.leftBarButtonItems = @[negativeSpacer,leftBarButtonItem];
    }else{
        self.navigationItem.leftBarButtonItems = @[leftBarButtonItem];
    }
    //设置修改按钮
    rightBtn = [[UIButton alloc]initWithFrame:CGRectMake(self.view.frame.size.width-40, 0, 40, 30)];
    
    [rightBtn setTitle:@"添加" forState:UIControlStateNormal];
    [rightBtn setTintColor:[UIColor whiteColor]];
    [rightBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
     UIImage *postBtn_bgImg = [UIImage imageNamed:@"postbtn_bg"];
    [rightBtn setBackgroundImage:[postBtn_bgImg stretchableImageWithLeftCapWidth:postBtn_bgImg.size.width*0.5f topCapHeight:postBtn_bgImg.size.height*0.5f] forState:UIControlStateNormal];
    [rightBtn addTarget:self action:@selector(addMore) forControlEvents:UIControlEventTouchUpInside];
    
    UIBarButtonItem *rightBarButtonItem = [[UIBarButtonItem alloc]initWithCustomView:rightBtn];

    if (ios7) {
        self.navigationItem.rightBarButtonItems = @[negativeSpacer,rightBarButtonItem];
    }else{
        self.navigationItem.rightBarButtonItems = @[rightBarButtonItem];
    }
    
    _catMangeTableView.delegate = self;
    _catMangeTableView.dataSource = self;
    
    state = @"";//默认无状态
    // 加载选项卡
    HMSegmentedControl *segmentedControl = [[HMSegmentedControl alloc] initWithSectionTitles:@[@"新闻", @"人才", @"视频", @"产品", @"图片",@"服务"]];
    selectedIndex = 0;
    
    [segmentedControl setIndexChangeBlock:^(NSUInteger index) {
        [_catMangeTableView headerEndRefreshing];
        
        selectedIndex = index;
        
        // 切换页面 每次一进入页面就下拉刷新
        [_catMangeTableView headerBeginRefreshing];
    }];
    [segmentedControl setFrame:CGRectMake(0, 0, self.view.bounds.size.width, 35)];
    [self.view addSubview:segmentedControl];
    
    /* 请求相应的选择类别数据 */
    // 初始化服务类
    cls_ = [[CatListService alloc]init];
    cls_.delegate = self;
    
    cls_.selectedIndex = selectedIndex;
    
    // 屏幕适配
    _catMangeTableView.frame = CGRectMake(_catMangeTableView.frame.origin.x, _catMangeTableView.frame.origin.y, _catMangeTableView.bounds.size.width, self.view.bounds.size.height-_catMangeTableView.frame.origin.y-20);
    
    _catMangeTableView.rowHeight = 80;
    
    // 集成刷新控件
    [self setupRefresh];
    
    [_catMangeTableView headerBeginRefreshing];
    
    catMArr=[[NSMutableArray alloc]initWithObjects:@"新闻类别", nil];
    //设置对话框边线
    catnameChangeViewSmall.layer.borderColor=[UIColor grayColor].CGColor;
    catnameChangeViewSmall.layer.borderWidth=1;

}

/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [_catMangeTableView addHeaderWithTarget:self action:@selector(headerRereshing)];
    /* 自动刷新(一进入程序就下拉刷新) */
    //[_tableView headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [_catMangeTableView addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    // 检查网络
    if (cls_.isQuery || ![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_catMangeTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_catMangeTableView headerEndRefreshing];
        
        return;
    }
    
    // 下拉刷新 （请求第一页数据）
    
    // 每次必须重置下 否则会数据混乱
    cls_.pageInfo.pageno = @"1";
    [cls_ pageQueryWithSelectedIndex:selectedIndex];
}

- (void)footerRereshing
{
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
        // 刷新表格
        [_catMangeTableView reloadData];
        
        // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
        [_catMangeTableView footerEndRefreshing];
        
        return;
    }
    
    // 如果正在查询 或 没有更多数据了
    if (cls_.isQuery || !cls_.pageInfo.hasMoreData) {
        // 2. 1秒后刷新表格UI
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(1.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            // 刷新表格
            [_catMangeTableView reloadData];
            
            // (最好在刷新表格后调用)调用endRefreshing可以结束刷新状态
            [_catMangeTableView footerEndRefreshing];
            
            MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
            hud.labelText = @"没有更多数据了";
            [hud hide:YES afterDelay:1];
        });
        
        cls_.pageInfo.hasMoreData = YES;
        return;
    }
    
    // 如果还有更多数据 请求下一页
    [cls_.pageInfo nextPage];
    [cls_ pageQueryWithSelectedIndex:selectedIndex];

}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

//
#pragma mark - Custom Method

//返回
-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
//进去共享设置
-(void)inShare:(id)sender{
    UIButton *Btn = sender;
    selectRow = Btn.tag - 10;//修改行数
    ShareSettingViewController *ssvc = [[ShareSettingViewController alloc]initWithNibName:(IPHONE5?@"ShareSettingViewController":@"ShareSetting_3.5") bundle:Nil];
    ssvc.tid = cls_.pageInfo.dataArr[selectRow][@"tid"];
    ssvc.mid = selectedIndex;
    ssvc.tName = cls_.pageInfo.dataArr[selectRow][@"tname"];
    [self.navigationController pushViewController:ssvc animated:YES];
}
//修改类别
-(void)alterBtnClick:(id)sender{
    rightBtn.hidden=YES;
    UIButton *btn=sender;
    selectRow = btn.tag;//修改行数
    CatMangeCell *cell = (CatMangeCell *)[[[btn superview]superview]superview ];
    _indexPath = [_catMangeTableView indexPathForCell:cell];
    
    [self.view bringSubviewToFront:catnameChangeView];
    newCatNameTF.text = cls_.pageInfo.dataArr[selectRow][@"tname"];
    deleteLbl.hidden=YES;
    catlblName.hidden=NO;
    newCatNameTF.hidden=NO;
    titlelbl.text=@"修改类别";
}
//删除类别
-(void)deleteBtnClick:(id)sender{
    
    rightBtn.hidden=YES;
    UIButton *btn = sender;
    selectRow = btn.tag;//删除行数
    CatMangeCell *cell = (CatMangeCell *)[[[btn superview]superview]superview ];
    _indexPath = [_catMangeTableView indexPathForCell:cell];

[self.view bringSubviewToFront:catnameChangeView];
    deleteLbl.hidden=NO;
    catlblName.hidden=YES;
    newCatNameTF.hidden=YES;
    titlelbl.text=@"删除类别";

}
//增加类别
-(void)addMore{
    rightBtn.hidden=YES;
 [self.view bringSubviewToFront:catnameChangeView];
    deleteLbl.hidden=YES;
    catlblName.hidden=NO;
    newCatNameTF.hidden=NO;
    titlelbl.text=@"添加类别";

}
#pragma mark - IBAction Method

- (IBAction)cancelBtnClick:(id)sender {
    rightBtn.hidden=NO;
    
    [self.view sendSubviewToBack:catnameChangeView];
}
- (IBAction)saveBtnClick:(id)sender {
    CatMangeCell *cell = ( CatMangeCell *)[_catMangeTableView cellForRowAtIndexPath:_indexPath];
    if ([titlelbl.text isEqualToString:@"修改类别"]) {
        state = @"修改";
        UILabel *lbl=(UILabel *)[cell.contentView viewWithTag:2];
        if (newCatNameTF.text.length!=0) {
            lbl.text=newCatNameTF.text;
            _indexPath=nil;
            //newCatNameTF.text=nil;
            [self.view sendSubviewToBack:catnameChangeView];
            rightBtn.hidden=NO;
            [self postInformation];
        }
        
    }else if([titlelbl.text isEqualToString:@"删除类别"]){
        state = @"删除";
//        [self tableView:_catMangeTableView commitEditingStyle:UITableViewCellEditingStyleDelete forRowAtIndexPath:_indexPath];
        [self.view sendSubviewToBack:catnameChangeView];
        rightBtn.hidden=NO;
        [self postInformation];
    }else{
        state = @"添加";
        if (newCatNameTF.text.length!=0) {
            [catMArr addObject:newCatNameTF.text];
            //newCatNameTF.text=nil;
            [self.view sendSubviewToBack:catnameChangeView];
            //[_catMangeTableView reloadData];
            rightBtn.hidden=NO;
            //发送添加请求
            [self postInformation];
        }
    }
}


#pragma mark - UITableView Delegate Method

-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath{
    return NO;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString *cellId = @"catMangeCell";
    
    CatMangeCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
    if (!cell) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"CatMangeCell" owner:nil options:nil][0];
    }
    NSUInteger row = [indexPath row];
    cell.shareBtn.tag = 10 + row;
    [cell.shareBtn addTarget:self action:@selector(inShare:) forControlEvents:UIControlEventTouchUpInside];

    [cell.alterBtn addTarget:self action:@selector(alterBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.alterBtn.tag = row;
    [cell.deleteBtn addTarget:self action:@selector(deleteBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    cell.deleteBtn.tag = row;
    UILabel *lbl=(UILabel *)[cell.contentView viewWithTag:2];
    lbl.text= cls_.pageInfo.dataArr[row][@"tname"];//catMArr[row];
    //添加图片
    UIImageView *img_view = (UIImageView *)[cell.contentView viewWithTag:1];
    img_view.image = [UIImage imageNamed:@"item_64"];
    
    return cell;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return cls_.pageInfo.dataArr.count;//catMArr.count;
}

-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath{
    
    NSInteger row=indexPath.row ;
    
    [cls_.pageInfo.dataArr removeObjectAtIndex:row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];


}

#pragma mark - QuestionService Delegate
// 请求成功
- (void)didRecieveData{
    [loadHud hide:YES];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
    [_catMangeTableView headerEndRefreshing];
    [_catMangeTableView footerEndRefreshing];
    [_catMangeTableView reloadData];
}

// 请求失败
- (void)didRecieveMsg{
    [loadHud hide:YES];
    self.navigationItem.rightBarButtonItem.enabled = YES;
    
    [_catMangeTableView headerEndRefreshing];
    [_catMangeTableView footerEndRefreshing];
}
//发送请求
- (void)postInformation {
    
    // 检查网络
    if (![Constants isExistenceNetwork]) {
        
    } else {
        if([state isEqualToString:@"添加"]){
            switch (selectedIndex) {
                case 0://新闻
                    action = @"newstypeadd";
                    break;
                case 1://人才
                    action = @"zhaopintypeadd";
                    break;
                case 2://视频
                    action = @"videotypeadd";
                    break;
                case 3://产品
                    action = @"prostypeadd";
                    break;
                case 4://图片
                    action = @"casetypeadd";
                    break;
                case 5://服务
                    action = @"serinfortypeadd";
                    break;
                default:
                break;
            }
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在添加，请稍后...";
                }
            
                    addCat = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                    addCat.requestMethod = @"POST";
                    // 设置超时时间
                    addCat.timeOutSeconds = 60;
                    addCat.delegate = self;
                    // 设置参数
                    NSLog(@"%@",newCatNameTF.text);
                    paramsDict = [NSMutableDictionary dictionary];
                    paramsDict = @{@"uid":UNAME,@"tname":newCatNameTF.text};//uid会员名;tname:类别名称
                    NSString *paramsStr = [NSString JSONString:paramsDict];
                    NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
                    NSData *paramsData = [result toGBKEncodingData];
                    addCat.postBody = [paramsData mutableCopy];
            
                    [addCat startAsynchronous];
            }
        else if ([state isEqualToString:@"修改"]){
            switch (selectedIndex) {
                case 0://新闻
                    action = @"newstypeupdate";
                    break;
                case 1://人才
                    action = @"zhaopintypeupdate";
                    break;
                case 2://视频
                    action = @"videotypeupdate";
                    break;
                case 3://产品
                    action = @"prostypeupdate";
                    break;
                case 4://图片
                    action = @"casetypeupdate";
                    break;
                case 5://服务
                    action = @"serinfortypeupdate";
                    break;
                default:
                    break;
            }
            if (!postHud || postHud.hidden == YES) {
                // 提示正在加载数据...
                postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                postHud.labelText = @"正在修改，请稍后...";
            }
            
            alterCat = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
            alterCat.requestMethod = @"POST";
            // 设置超时时间
            alterCat.timeOutSeconds = 60;
            alterCat.delegate = self;
            // 设置参数
            paramsDict = [NSMutableDictionary dictionary];
            paramsDict = @{@"tid":cls_.pageInfo.dataArr[selectRow][@"tid"],@"uid":UNAME,@"tname":newCatNameTF.text};
            NSString *paramsStr = [NSString JSONString:paramsDict];
            NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
            
            NSData *paramsData = [result toGBKEncodingData];
            alterCat.postBody = [paramsData mutableCopy];
            
            [alterCat startAsynchronous];
            
        }else if([state isEqualToString:@"删除"]){
                switch (selectedIndex) {
                    case 0://新闻
                        action = @"newstypedel";
                        break;
                    case 1://人才
                        action = @"zhaopintypedel";
                        break;
                    case 2://视频
                        action = @"videotypedel";
                        break;
                    case 3://产品
                        action = @"prostypedel";
                        break;
                    case 4://图片
                        action = @"casetypedel";
                        break;
                    case 5://服务
                        action = @"serinfortypedel";
                        break;
                    default:
                        break;
                }
                if (!postHud || postHud.hidden == YES) {
                    // 提示正在加载数据...
                    postHud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
                    postHud.labelText = @"正在删除，请稍后...";
                }
                
                alterCat = [[ASIFormDataRequest alloc]initWithURL:[NSURL URLWithString:API_STR]];
                alterCat.requestMethod = @"POST";
                // 设置超时时间
                alterCat.timeOutSeconds = 60;
                alterCat.delegate = self;
                // 设置参数
                paramsDict = [NSMutableDictionary dictionary];
                paramsDict = @{@"tid":cls_.pageInfo.dataArr[selectRow][@"tid"],@"uid":UNAME};
                NSString *paramsStr = [NSString JSONString:paramsDict];
                NSString *result = [NSString stringWithFormat:TEMPLATE_PARAMSTR, action,paramsStr];
                
                NSData *paramsData = [result toGBKEncodingData];
                alterCat.postBody = [paramsData mutableCopy];
                
                [alterCat startAsynchronous];
                
        }
    }
}
#pragma mark - ASIHttpRequestDelegate method

- (void)requestFinished:(ASIHTTPRequest *)request {
    NSLog(@"%@",request.responseString);
 
    NSError *err;
    NSDictionary *result = [NSJSONSerialization JSONObjectWithData:[request.responseString dataForUTF8] options:NSJSONReadingAllowFragments error:&err];
    
    // 1. 是否解析有错误
    if (!err) {
        
        // 2. 判断错误码
        NSInteger errorCode = [result[@"errorCode"]integerValue];
        if (errorCode == 0) {
            postHud.hidden = YES;
            //获取选中删除行索引值并通过获取的索引值删除数组中的值
            if ([state isEqualToString:@"添加"]) {
                
                cls_.pageInfo.pageno = @"1";
                [cls_ pageQueryWithSelectedIndex:selectedIndex];
            
                [_catMangeTableView reloadData];
            
            [SVProgressHUD showSuccessWithStatus:@"成功"];
                newCatNameTF.text = nil;//成功后置空
            }
            else if([state isEqualToString:@"删除"]){
                cls_.pageInfo.pageno = @"1";
                [cls_ pageQueryWithSelectedIndex:selectedIndex];
                
                [_catMangeTableView reloadData];
                
                [SVProgressHUD showSuccessWithStatus:@"成功"];
            }
            else{
                cls_.pageInfo.pageno = @"1";
                [cls_ pageQueryWithSelectedIndex:selectedIndex];
                
                [_catMangeTableView reloadData];
                newCatNameTF.text = nil;//成功后置空
                [SVProgressHUD showSuccessWithStatus:@"成功"];
            }
        } else {
            [SVProgressHUD showErrorWithStatus:result[@"errorMsg"]];
        }
    } else {
        [SVProgressHUD showErrorWithStatus:@"数据解析出错！"];
    }
}

- (void)requestFailed:(ASIHTTPRequest *)request{
    [SVProgressHUD showErrorWithStatus:@"服务器无法访问，请稍后再试!"];
}

-(void)dealloc{
    postHud = nil;
    cls_ = nil;
    [addCat cancel];
    [delegateCat cancel];
    [alterCat cancel];
}

@end
